package com.jxb.algorithm;

import com.google.common.collect.Range;
import org.apache.shardingsphere.api.sharding.complex.ComplexKeysShardingAlgorithm;
import org.apache.shardingsphere.api.sharding.complex.ComplexKeysShardingValue;

import java.math.BigInteger;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;

/**
 * 复杂表分片策略：course_$->{((cid+1)%4).intdiv(2)+1 + (30-20)+1}
 *  路由的表：12,13
 */
public class MyComplexTableShardingAlgorithm implements ComplexKeysShardingAlgorithm<Long> {
    @Override
    public Collection<String> doSharding(Collection<String> collection, ComplexKeysShardingValue<Long> shardingValue) {
        //实现按照 Between 进行范围分片。
        //例如 select * from course where cid in (1,3,5) and userid Between 200 and 300;
        Collection<Long> cidCol = shardingValue.getColumnNameAndShardingValuesMap().get("cid");
        Range<Long> uageRange = shardingValue.getColumnNameAndRangeValuesMap().get("user_id");

        List<String> result = new ArrayList<>();

        Long lowerEndpoint = uageRange.lowerEndpoint();//200
        Long upperEndpoint = uageRange.upperEndpoint();//300
        Long diff = upperEndpoint - lowerEndpoint;
        //实现自定义分片逻辑 例如可以自己实现 course_$->{((cid+1)%4).intdiv(2)+1 + (30-20)+1} 这样的复杂分片逻辑
        for(Long cid : cidCol){
            BigInteger cidI = BigInteger.valueOf(cid);
            BigInteger add = (((((cidI.add(new BigInteger("1")))
                    .mod(new BigInteger("4")))
                    .divide(new BigInteger("2")))
                    .add(new BigInteger("1")))
                    .add(new BigInteger(String.valueOf(diff))))
                    .add(new BigInteger("1"));
            result.add("course_"+add);
        }
        return result;
    }
}
